import {HttpClient, HttpHeaders, HttpResponse} from '@angular/common/http';
import {Injectable} from '@angular/core';
import {environment} from "../../environments/environment";
import {UserInfo} from "../modals/basic.modal";
import {Observable} from "rxjs";

@Injectable({
    providedIn: 'root'
})

export class BasicService {

    basicUrl = environment.basicUrl;
    userData: UserInfo;

    constructor(
        private http: HttpClient,
    ) {
    }

    private static handleSuccess(res: HttpResponse<any>) {
        BasicService.setToken(res);
        const limitCode = [127];
        if (res.body && res.body.code !== 0 && !limitCode.includes(res.body.code)) {
            // this.notification.create('warning', '提示', res.body.msg);
        }
        return res.body;
    }

    private static setToken(res: HttpResponse<Response>) {
        const token = res.headers.get('access_token');
        if (token) {
            localStorage.setItem('currentToken', token);
        }
    }

    public currentUser(type = '', data = null, value = '') {
        if (data) {
            this.userData = data;
        }
        if (type && value) {
            this.userData[type] = value;
        }
        return type && this.userData && this.userData[type] ? this.userData[type] : '';
    }

    getToken() {
        const currentToken = localStorage.getItem('currentToken');
        return currentToken && currentToken !== 'null' ? currentToken : '';
    }

    getServiceUrl(path) {
        return `${this.basicUrl}/${path}`;
    }

    regroupFormData(obj, isArray = false) {
        const formData = new FormData();
        if (isArray) {
            obj.map(item => {
                Object.keys(item).map(key => {
                    formData.append(key, item[key]);
                });
            })
        } else {
            Object.keys(obj).map(key => {
                formData.append(key, obj[key]);
            });
        }
        return formData;
    }

    // general http fun
    postData(path: string, params: any = null, array = false) {
        const url = this.getServiceUrl(path);
        const formData = params ? this.regroupFormData(params, array) : params;
        return this.http.post(url, formData, {
            observe: 'response',
        }).toPromise().then(BasicService.handleSuccess);
    }

    // general http fun
    getData(path: string, filterData: any = null) {
        const url = this.getServiceUrl(path);
        const searchData = {};
        if (filterData) {
            Object.keys(filterData).map(item => {
                if (filterData[item]) {
                    searchData[item] = filterData[item];
                }
            });
            if (searchData) {
                return this.http.get(url, {
                    params: {...searchData}
                });
            }
        } else {
            return this.http.get(url);
        }
    }

    postJsonData(path, data): Observable<any> {
        const linkJson = JSON.stringify(data);
        const contentTypeHeader = new HttpHeaders().set('Content-Type', 'application/json')
            .set('Accept', 'application/json');
        const url = this.getServiceUrl(path);

        return this.http.post<any>(url, linkJson, {headers: contentTypeHeader});
    }

    postDataWithToken(path: string, params: any = null, array = false){
        const url = this.getServiceUrl(path);
        const token = this.getToken(); // token保存在localstorage
        const formData = params ? this.regroupFormData(params, array) : params;

        const contentTypeHeader = new HttpHeaders()
            .set('Authorization', token);
        return this.http.post(url, formData, {
            headers: contentTypeHeader,
            observe: 'response',
        }).toPromise().then(BasicService.handleSuccess);
    }

    postSingleFile(path, params): Observable<any> {
        const url = this.getServiceUrl(path);
        return this.http.post(url, params);
    }
}
